﻿using CIS.Web.Properties;
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace CIS.Web.Common
{
	public class MailSender : IDisposable
	{
		SmtpClient _smtp;

		public MailSender(string smtpServer)
		{
			_smtp = new SmtpClient(smtpServer);
		}

		public string SendMail(MailAddress from, MailMessage message, string password)
		{
			var str = string.Empty;
			try
			{
				ServicePointManager.ServerCertificateValidationCallback = delegate (object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
				{
					return true;
				};

				message.From = from;
				_smtp.Credentials = new NetworkCredential(from.Address, password);
				_smtp.EnableSsl = true;
				//_smtp.Port = 465;
				_smtp.Send(message);
				return string.Empty;
			}
			catch (SmtpException ex)
			{
				if (ex.StatusCode == SmtpStatusCode.TransactionFailed)
				{
					str = Resources.SmtpException_TransactionFailed;
				}
				else if (ex.StatusCode == SmtpStatusCode.MailboxUnavailable)
				{
					str = Resources.SmtpException_MailboxUnavailable;
				}
				else if (ex.StatusCode == SmtpStatusCode.MailboxNameNotAllowed)
				{
					str = Resources.SmtpException_MailboxNameNotAllowed;
				}
				else if (ex.StatusCode == SmtpStatusCode.GeneralFailure)
				{
					str = Resources.SmtpException_GeneralFailure;
				}
				else
				{
					str = Resources.SmtpException_ContactManager;
				}
			}
			catch (Exception)
			{
				str = Resources.SmtpException_ContactManager;
			}

			return str;
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				// dispose managed resources
				if (_smtp != null)
				{
					_smtp.Dispose();
				}
			}
			// free native resources
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}
	}
}